package org.tigris.atlas.quizme.client.action;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.tigris.atlas.quizme.bizobj.AnswerBO;
import org.tigris.atlas.quizme.bizobj.QuestionBO;
import org.tigris.atlas.quizme.service.QuestionCollectionServiceResponse;
import org.tigris.atlas.quizme.service.QuizCollectionServiceResponse;
import org.tigris.atlas.quizme.service.delegate.EntityMaintenanceServiceDelegate;
import org.tigris.atlas.quizme.service.delegate.QuizServiceDelegate;
import org.tigris.atlas.quizme.service.delegate.ServiceDelegateFactory;
import org.tigris.atlas.quizme.transfer.Answer;
import org.tigris.atlas.quizme.transfer.Question;
import org.tigris.atlas.quizme.transfer.TransferObjectFactory;

public class LoadDatabaseAction  extends Action {
	public ActionForward execute(ActionMapping mapping, ActionForm form,
		      HttpServletRequest request, HttpServletResponse response) {	
		/*List questions = new ArrayList(160);
		try {
	        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver" );
	    } catch (Exception e) {
	        System.out.println("ERROR: failed to load HSQLDB JDBC driver.");
	        e.printStackTrace();
	        return mapping.findForward("success");
	    }
	    Connection c = null;
	    Statement s = null;
	    Statement s2 = null;
	    
	    try {
	    	c = DriverManager.getConnection("jdbc:odbc:rupexams", "", "");
	    	s = c.createStatement();
	    	ResultSet set = s.executeQuery("SELECT * FROM Questions");
		    while(set.next()){
		    	String question = set.getString("Question");
		    	int answerCount = set.getInt("AnswerCount");
		    	int questionId = set.getInt("ID");
		    	boolean mutliAnswer = set.getBoolean("MultiAnswer");
		    	
		    	Question questionTO = TransferObjectFactory.createQuestion();
		    	questionTO.setAnswerCount(new Integer(answerCount));
		    	questionTO.setQuestion(question);
		    	questionTO.setMultiAnswer(new Boolean(mutliAnswer));
		    	questionTO.setQuestionId(""+questionId);
		    	s2 = c.createStatement();
		 	    ResultSet set2 = s2.executeQuery("SELECT * FROM Answers WHERE QuestionID = "+questionId);
		 	 
		 	    while(set2.next()){
			    	String answer = set2.getString("Answer");
			    	boolean correct = set2.getBoolean("Correct");
			    	int confidence = set2.getInt("Confidence");
			    	int answerID = set2.getInt("AnswerID");
			    	
			    	Answer answerTO = TransferObjectFactory.createAnswer();
			    	answerTO.setAnswerId(""+answerID);
			    	answerTO.setQuestion(questionTO);
			    	answerTO.setAnswer(answer);
			    	answerTO.setConfidence(new Integer(confidence));
			    	answerTO.setCorrect(new Boolean(correct));
			    	questionTO.addAnswer(answerTO);
		 	    }
		 	    questions.add(questionTO);
		 	 
		    }
		    s.close();
		    s2.close();
		    c.close();
	    } catch (Exception e) {
	        System.out.println("ERROR: failed to load HSQLDB JDBC driver.");
	        e.printStackTrace();
	        try{
	        	s.close();
	        	s2.close();
	        	c.close();
	        }
	        catch(Exception es){}
	        return mapping.findForward("success");
	    }
	   
	     outputSQLFile(questions);
		return mapping.findForward("success");*/
		StringBuffer file = new StringBuffer(100); 
		QuizServiceDelegate emd = ServiceDelegateFactory.createQuizServiceDelegate();
		QuestionCollectionServiceResponse r = emd.selectAllQuestions();
		Collection questions = r.getItems();
		Iterator i = questions.iterator();
		while(i.hasNext()){
			QuestionBO question = (QuestionBO)i.next();
			
			if(question.getMultiAnswer().booleanValue()){
				file.append("<question type=\"multichoice\">\n");
			}
			else{
				file.append("<question type=\"singlechoice\">\n");
			}
			int subLength;
			int length = question.getQuestion().length();
			if(length < 20){
				subLength = length;
			}
			else subLength = 20;
			
			file.append("<name><text>"+question.getQuestion().substring(0,subLength)+"</text></name>\n");   
			file.append("<questiontext format=\"html\">\n");
			file.append("<text>"+question.getQuestion()+"</text>\n");
			file.append("</questiontext>\n");
			file.append("<image></image>\n");
			file.append("<generalfeedback>\n");
			file.append("<text></text>\n");
			file.append("</generalfeedback>\n");
			file.append("<defaultgrade>1</defaultgrade>\n");
			file.append("<penalty>1</penalty>\n");
			file.append("<hidden>0</hidden>\n");
			file.append("<shuffleanswers>1</shuffleanswers>\n");
			
			if(question.getMultiAnswer().booleanValue()){
				file.append("<single>false</single>\n");
			}
			else{
				file.append("<single>true</single>\n");
			}
			
			file.append("<shuffleanswers>true</shuffleanswers>\n");
			file.append("<correctfeedback>      <text></text>\n");
			file.append("</correctfeedback>\n");
			file.append("<partiallycorrectfeedback>      <text></text>\n");
			file.append("</partiallycorrectfeedback>\n");
			file.append("<incorrectfeedback>      <text></text>\n");
			file.append("</incorrectfeedback>\n\n");
			
			Set answers = question.getAnswers();
			Iterator j = answers.iterator();
			
			int correctAnswerFraction;
			int numCorrectAnswers = 0;
			
			while(j.hasNext()){
				AnswerBO answer = (AnswerBO)j.next();
				if(answer.getCorrect().booleanValue()){
					numCorrectAnswers++;
				}
			}
			
			correctAnswerFraction = 100/numCorrectAnswers;
			
			j = answers.iterator();
			while(j.hasNext()){
				AnswerBO answer = (AnswerBO)j.next();
				if(answer.getCorrect().booleanValue()){
					file.append("<answer fraction=\""+ correctAnswerFraction +"\">\n");
				}
				else{
					file.append("<answer fraction=\"0\">\n");
				}
				file.append("<shuffleanswers>true</shuffleanswers>\n");
				file.append("<text>\n");
				file.append(answer.getAnswer()+"\n");
				file.append("</text>\n");
				file.append("<feedback>\n");
				file.append("<text>\n");
				file.append("</text>\n");
				file.append("</feedback>\n");
				file.append("</answer>\n");
			}
			file.append("</question>\n");
		}
		
		
		try {
			FileWriter fw = new FileWriter(new File("C:\\questions.xml"));
			fw.write(file.toString());
			fw.flush();
			fw.close();
		} catch (IOException e) {
			//e.printStacktrace();
		}
		
		return mapping.findForward("success");
	}
	
	private void outputSQLFile(List questions){
		/*StringBuffer sql = new StringBuffer(100); 
		for(int i=0; i < questions.size(); i++){
			
			Question question = (Question)questions.get(i);
			sql.append("INSERT INTO QUESTION (QUESTION_ID, MULTI_ANSWER, QUESTION, ANSWER_COUNT) VALUES(");
			sql.append("'"+question.getQuestionId()+"',");
			sql.append(((question.getMultiAnswer().booleanValue())?"1":"0")+",");
			sql.append("'"+question.getQuestion()+"',");
			sql.append(question.getAnswerCount()+");\n");
			
			Set answers = question.getAnswers();
			Iterator j = answers.iterator();
			while(j.hasNext()){
				Answer answer = (Answer)j.next();
				sql.append("INSERT INTO ANSWER(ANSWER_ID, ANSWER, CONFIDENCE, CORRECT, QUESTION_ID) VALUES(");
				sql.append("'"+answer.getAnswerId()+"',");
				sql.append("'"+answer.getAnswer()+"',");
				sql.append(answer.getConfidence()+",");
				sql.append(((answer.getCorrect().booleanValue())?"1":"0")+",");
				sql.append(question.getQuestionId()+");\n");
			}
			
	    }
		try {
			FileWriter fw = new FileWriter(new File("C:\\question.sql"));
			fw.write(sql.toString());
			fw.flush();
			fw.close();
		} catch (IOException e) {
			//e.printStacktrace();
		}*/
		
	}
}